<?php

namespace App\Exports;

use App\Models\Download;
use App\Models\LoginHistory;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class UserLoginHistoryExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        return LoginHistory::query()
            ->select(['login_histories.created_at', 'login_histories.channel_id', 'login_histories.login_mode', 'frontend_users.mobile'])
            ->leftJoin('frontend_users', 'frontend_users.id', 'login_histories.user_id')
            ->where('agent_id', $this->data->agent_id)
            ->with(['channel'])
            ->when(!empty($this->request['keyword']), function ($q) {
                $likeVal = '%' . $this->request['keyword'] . '%';

                return $q->where('nickname', 'like', $likeVal)->orWhere('mobile', 'like', $likeVal);
            })
            ->when(!empty($this->request['channel_id']), function ($q) {
                return $q->where('login_histories.channel_id', $this->request['channel_id']);
            })
            ->when(!empty($this->request['login_mode']), function ($q) {
                return $q->where('login_histories.login_mode', $this->request['login_mode']);
            })
            ->when(!empty($this->request['start_date']), function ($q) {
                return $q->where('login_histories.created_at', '>=', Carbon::parse($this->request['start_date'])->startOfDay());
            })
            ->when(!empty($this->request['end_date']), function ($q) {
                return $q->where('login_histories.created_at', '<=', Carbon::parse($this->request['end_date'])->endOfDay());
            })
            ->orderByDesc('login_histories.id');
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        $value['mobile'] = ' ' . $value['mobile'];

        return [
            $value['mobile'] ?? '',
            $value['login_mode']->description,
            $value['channel']['name'] ?? '',
            $value['created_at'],
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            '手机号',
            '登录方式',
            '登录渠道',
            '登录时间',
        ];
    }
}
